#include "stdafx.h"
#include "SoundSystem.h"

using namespace MomogenkyouSystem;

AUDIODEVICE		SoundSystem::g_pDevice(NULL);
AUDIOSTREAM		SoundSystem::g_pBGMStream(NULL);
std::string		SoundSystem::g_CurrentBGMFile("NULL");

bool		SoundSystem::Initialize(const HWND		& param_WindowHandle, 
								const HINSTANCE & param_WindowInstance)
{
	UNREFERENCED_PARAMETER(param_WindowHandle);
	UNREFERENCED_PARAMETER(param_WindowInstance);

	g_pDevice = audiere::OpenDevice();
	ASSERT(g_pDevice != NULL, "Failed to open Audiere Device");
	return true;
}

void		SoundSystem::Shutdown()
{
	WriteCommandLine("SoundSystem > Shutdown");
}


void		SoundSystem::PlayBGM(const std::string & Filename)
{
	std::string	_Filename = System_Utility::LowerCase(Filename);
	if(Filename == g_CurrentBGMFile)
	{
		WriteCommandLine("Identical BGM");
		return;
	}
	if(g_pBGMStream)
		if(g_pBGMStream->isPlaying())
			g_pBGMStream->stop();
		
	audiere::FilePtr			_pFile	=	audiere::OpenFile(_Filename.c_str(), false);
	audiere::SampleSourcePtr	_pSample=	audiere::OpenSampleSource(_pFile);

	ASSERT(_pFile != NULL, "Failed to create Sound Effect");

	g_pBGMStream = audiere::OpenSound(g_pDevice, _pSample, true);
	g_pBGMStream->setRepeat(true);
	g_pBGMStream->setVolume(0.9f);
	g_pBGMStream->play();
	//g_pBGMStream->setPosition(1024);

	_pFile		= NULL;
	_pSample	= NULL;

	g_CurrentBGMFile = _Filename;
}

void		SoundSystem::StopBGM()
{
	if(g_pBGMStream == NULL)	return;
	g_pBGMStream->stop();
}

void		SoundSystem::SetBGMVolume(const float & fVolume)
{
	g_pBGMStream->setVolume(fVolume);
}

SOUNDEFFECT	SoundSystem::CreateSoundEffect(const std::string & Filename, const audiere::SoundEffectType & Type)
{
	std::string	_Filename = System_Utility::LowerCase(Filename);

	audiere::FilePtr			_pFile	=	audiere::OpenFile(_Filename.c_str(), false);
	audiere::SampleSourcePtr	_pSample=	audiere::OpenSampleSource(_pFile);
	
	ASSERT(_pFile != NULL, "Failed to create Sound Effect");

	SOUNDEFFECT	_pSoundEffect(NULL);
	_pSoundEffect = audiere::OpenSoundEffect(g_pDevice, _pSample, Type);

	_pSoundEffect->setVolume(1.0f);
	//_pSoundEffect->play();

	_pFile		= NULL;
	_pSample	= NULL;

	return	_pSoundEffect;
}

void		SoundSystem::DeleteSoundEffect(SOUNDEFFECT	pEffect)
{
	pEffect->stop();
	pEffect = NULL;
}

void		SoundSystem::Update(const float &fInterval)
{
	UNREFERENCED_PARAMETER(fInterval);
	g_pDevice->update();
}